#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""小程序图片上传专用接口 (开发阶段版本)
目标：
1. 明确分类，拒绝未指定或非法分类。
2. 不做任何历史兼容/兜底；错误立即返回。
3. 仅接受字段名 image （统一规范）。
4. 返回: { success: True, data: { url: <relative_url> } }
"""
from flask import request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity
from . import miniprogram_bp
from backend.services.media_service import MediaService
from backend.config.upload_config import UploadConfig
from backend.services.unified_log_service import log_service
import os

_ALLOWED_CATEGORIES = { 'avatar', 'social', 'communication', 'intervention', 'feedback' }

@miniprogram_bp.route('/upload/image', methods=['POST'])
@jwt_required()
def upload_image_strict():
    try:
        user_id = int(get_jwt_identity())
        # 分类必须显式给出: formData.category 或 query category
        category = (request.form.get('category') or request.args.get('category') or '').strip().lower()
        if not category:
            return jsonify({'success': False, 'message': '缺少分类(category)'}), 400
        if category not in _ALLOWED_CATEGORIES:
            return jsonify({'success': False, 'message': f'非法分类: {category}'}), 400

        if 'image' not in request.files:
            return jsonify({'success': False, 'message': '缺少文件字段 image'}), 400
        file = request.files['image']
        if not file.filename:
            return jsonify({'success': False, 'message': '空文件名'}), 400

        if not UploadConfig.is_allowed_file(file.filename):
            return jsonify({'success': False, 'message': '仅支持 JPG/JPEG/PNG/GIF/WEBP'}), 400

        # 保存
        rel_url, physical_path = MediaService.save_image(file, category)
        saved_size = os.path.getsize(physical_path)
        min_size = UploadConfig.get_min_file_size(is_dev_mode=True)
        if saved_size < min_size:
            try:
                os.remove(physical_path)
            except Exception:
                pass
            return jsonify({'success': False, 'message': '文件过小/疑似损坏'}), 400

        # 记录
        try:
            log_service.log_operation(
                user_id=user_id,
                action='UPLOAD',
                table_name='files',
                record_id=None,
                details=f'upload {os.path.basename(physical_path)} cat={category} size={saved_size}'
            )
        except Exception:
            pass

        return jsonify({'success': True, 'data': { 'url': rel_url }})
    except Exception as e:
        current_app.logger.error(f'[upload_image_strict] failed: {e}')
        return jsonify({'success': False, 'message': '上传失败'}), 500
